package com.sx.micowell.module.homePage

import android.annotation.SuppressLint

import android.view.View
import androidx.core.view.get
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.gyf.immersionbar.ImmersionBar
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.Calendar.Scheme
import com.haibin.calendarview.CalendarView
import com.miloyu.modelnet.response.DictType
import com.miloyu.modelnet.response.LearnedCourseVO
import com.miloyu.modelnet.response.TrainListVO
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.FragPlanBinding

import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.PlanModel
import com.sx.micowell.framework.model.TrainPlanModel
import com.sx.micowell.framework.tools.AppDialogUtils
import com.sx.micowell.module.MainActivity
import com.sx.micowell.module.trainplan.TrainPlanListAdapter
import com.sx.micowell.module.trainplan.TrainTypeListAdapter
import com.sx.widget.app.DisplayUtil
import kotlinx.android.synthetic.main.frag_home.*
import kotlinx.android.synthetic.main.frag_plan.view.*

/**
 * @Description 主页-计划
 * @Author 梁浩文
 * @Date 2021/7/27 9:15
 */
@Route(path = RoutePath.Plan)
class PlanFragment : MyFragment<FragPlanBinding, MainActivity>() , CalendarView.OnCalendarSelectListener,
                                                                        CalendarView.OnMonthChangeListener,
                                                                        CalendarView.OnViewChangeListener {

    lateinit var viewModel: PlanModel

    private var trainPlanListAdapter : TrainPlanListAdapter? = null

    private var year: Int = 0

    private var month: Int = 0

    private var day: Int = 0

    override fun initViewModel() {
        viewModel = getActivityScopeViewModel(PlanModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_plan, BR.viewModel, viewModel)
    }

    override fun initView() {
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(binding.refreshLayout).init()

        binding.calendarView.setOnCalendarSelectListener(this)
        binding.calendarView.setOnMonthChangeListener(this)
        binding.calendarView.setOnViewChangeListener(this)
        childFragmentManager.beginTransaction().add(
            R.id.home_frag,RouteManager.getInstance()
                .getRecommendCourseFragment()).commit()
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {

        year = binding.calendarView.curYear
        month = binding.calendarView.curMonth
        day = binding.calendarView.curDay

        binding.tvYear.text = "${year}年${month}月"

        viewModel.dateStr = "${year}/${month}/${day}"

        viewModel.monthPlanState("${year}/${month}/${day}")

        // 今天
        binding.stuActScheduleToday.setOnClickListener {
            binding.calendarView.scrollToCurrent()
        }

        // 上一个月
        binding.calendarLeft.setOnClickListener {
            binding.calendarView.scrollToPre()
        }

        // 下一个月
        binding.calendarRight.setOnClickListener {
            binding.calendarView.scrollToNext()
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        // 刷新
        viewModel.ui.refreshEvent.observe(this, {
            binding.refreshLayout.finishRefresh(it)
        })
        viewModel.addPlanSuccess.observe(this, {
            viewModel.monthPlanState("${year}/${month}/${day}")
        })

        setPlanState()
        setTrainPlanList()
        deleteState()
    }

    private fun setPlanState() {
        val map : HashMap<String, Calendar> = HashMap()
        viewModel.planStatusEvent.observe(this, {
            map.clear()
            it.forEach {data ->
                val valueStr = data.targetTime.split("-")
                when {
                    valueStr[2].toInt() == binding.calendarView.curDay -> {
                        map[getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                            valueStr[2].toInt(), data.planStatus).toString()] =
                            getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                                valueStr[2].toInt(), "3")
                    }
                    valueStr[2].toInt() >= binding.calendarView.curDay -> {
                        map[getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                            valueStr[2].toInt(), data.planStatus).toString()] =
                            getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                                valueStr[2].toInt(), "4")
                    }
                    else -> {
                        map[getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                            valueStr[2].toInt(), data.planStatus).toString()] =
                            getSchemeCalendar(valueStr[0].toInt(), valueStr[1].toInt(),
                                valueStr[2].toInt(), data.planStatus)
                    }
                }
            }
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            binding.calendarView.setSchemeDate(map)
        })
    }

    private fun setTrainPlanList() {
        //取消recyclerview单独的滑动效果
        binding.recyclerTrainPlan.isNestedScrollingEnabled = false
        //设置布局管理器
        binding.recyclerTrainPlan.layoutManager = LinearLayoutManager(context)

        viewModel.trainListEvent.observe(this, {

            if (it.size > 0) {
                binding.layoutEmpty.visibility = View.GONE
                if (trainPlanListAdapter == null) {
                    trainPlanListAdapter = TrainPlanListAdapter()
                    trainPlanListAdapter?.data?.clear()
                    trainPlanListAdapter?.data = it
                    binding.recyclerTrainPlan.adapter = trainPlanListAdapter

                    trainPlanListAdapter?.addChildClickViewIds(R.id.image_delete)
                    trainPlanListAdapter?.setOnItemChildClickListener { adapter, view, position ->
                        val trainBean: TrainListVO = adapter.getItem(position) as TrainListVO
                        if(view.id==R.id.image_delete){
                            AppDialogUtils.showBasicDialog(
                                context, "提示", "确定要删除该计划吗？",
                                object : AppDialogUtils.IOnClickListener {
                                    override fun leftListener() {}
                                    override fun rightListener() {
                                        viewModel.deletePlan(trainBean.id, "${year}/${month}/${day}")
                                    }
                                })
                        }
                    }

                    trainPlanListAdapter?.setOnItemClickListener { adapter, view, position ->
                        AppDialogUtils.showBasicDialog(
                            context, "提示", "是否要开始训练？",
                            object : AppDialogUtils.IOnClickListener {
                                override fun leftListener() {}
                                override fun rightListener() {
                                    myActivity.binding.mainNavigation.selectedItemId=R.id.action_train
                                }
                            })
                    }

                } else {
                    trainPlanListAdapter?.data = it
                    binding.recyclerTrainPlan.adapter = trainPlanListAdapter
                }

            } else {
                binding.recyclerTrainPlan.adapter = null
                binding.layoutEmpty.visibility = View.VISIBLE
            }
        })

    }

    private fun deleteState() {
        viewModel.deleteSuccessEvent.observe(this, {
            viewModel.monthPlanState("${year}/${month}/${day}")
        })
    }

    private fun getSchemeCalendar(year:Int, month:Int, day: Int, text:String): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.scheme = text
        calendar.addScheme(Scheme())
        return calendar
    }


    @SuppressLint("SetTextI18n")
    override fun onMonthChange(year: Int, month: Int) {
        binding.tvYear.text = year.toString() + "年" + month.toString() + "月"
        viewModel.monthPlanState("${year}/${month}/${binding.calendarView.curDay}")
        viewModel.dateStr = "${year}/${month}/${day}"
    }

    override fun onCalendarOutOfRange(calendar: Calendar?) {

    }

    override fun onCalendarSelect(calendar: Calendar?, isClick: Boolean) {
        year = calendar!!.year
        month = calendar.month
        day = calendar.day

        viewModel.dayPlanList("${calendar.year}/${calendar.month}/${calendar.day}")
        viewModel.dateStr = "${year}/${month}/${day}"
    }

    override fun onViewChange(isMonthView: Boolean) {
        binding.refreshLayout.setEnableRefresh(isMonthView)
    }

}